<template>
  <div class="system-management">
    <!-- 新增项目按钮 -->
    <el-button type="primary" @click="handleAdd">新增项目</el-button>
    
    <!-- 系统列表 -->
    <el-table :data="systems" border style="width: 100%" v-loading="loading">
      <el-table-column prop="systemName" label="系统名称" width="180"></el-table-column>
      <el-table-column prop="description" label="系统描述"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="formatStatus" width="120"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button @click="handleEdit(row)" size="small" type="primary">编辑</el-button>
          <el-button @click="handleDelete(row)" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryData.pageNum"
        v-model:page-size="queryData.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        size="default"
        :disabled="disabled"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="formData" 
        ref="formRef" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="图标" prop="icon">
          <el-select 
            v-model="formData.icon" 
            placeholder="请选择图标"
            filterable
            clearable
          >
            <el-option
              v-for="icon in elementIcons"
              :key="icon"
              :value="icon"
              :label="icon"
            >
              <div style="display: flex; align-items: center; gap: 10px;">
                <el-icon><component :is="ElementPlusIcons[icon]" /></el-icon>
                <span>{{ icon }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="formData.systemName" placeholder="请输入系统名称"></el-input>
        </el-form-item>
        <el-form-item label="系统描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入系统描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getSystemList, addSystem, deleteSystem } from '@/api/system';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

export default {
  name: 'SystemManagement',
  data() {
    return {
      loading: false,
      disabled: false,
      submitting: false,
      dialogVisible: false,
      dialogTitle: '新增项目',
      isEditMode: false,
      queryData: {
        pageNum: 1,
        pageSize: 10,
        orderBy: ''
      },
      total: 0,
      ElementPlusIcons: ElementPlusIconsVue, // 将图标集合暴露给模板
      elementIcons: Object.keys(ElementPlusIconsVue),
      formData: {
        systemCode: '',
        systemName: '',
        description: '',
        status: 1,
        icon: ''
      },
      rules: {
        systemName: [
          { required: true, message: '请输入系统名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '不能超过200个字符', trigger: 'blur' }
        ],
        icon: [{ required: true, message: '请选择图标', trigger: 'blur' }],
      },
      systems: []
    };
  },
  methods: {
    // 获取系统列表
    async fetchSystems() {
      this.loading = true;
      try {
        const res = await getSystemList(this.queryData);
        this.systems = res.data.list || [];
        this.total = res.data.total || 0;
      } catch (error) {
        console.error('获取系统列表失败:', error);
        this.$message.error('获取系统列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 新增项目
    handleAdd() {
      this.dialogTitle = '新增项目';
      this.isEditMode = false;
      this.formData = {
        systemCode: '',
        systemName: '',
        description: '',
        status: 1,
        icon: ''
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate();
      });
    },
    
    // 编辑项目
    handleEdit(row) {
      this.dialogTitle = '编辑项目';
      this.isEditMode = true;
      this.formData = { ...row };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate();
      });
    },
    
    // 删除项目
    handleDelete(row) {
      this.$confirm('确认删除该系统吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteSystem(row.systemCode); // 假设根据systemCode删除
          this.$message.success('删除成功');
          this.fetchSystems();
        } catch (error) {
          this.$message.error('删除失败');
        }
      }).catch(() => {});
    },
    
    // 提交表单
    async submitForm() {
      try {
        const valid = await this.$refs.formRef.validate();
        if (!valid) return;
        
        this.submitting = true;
        const apiMethod = this.isEditMode ? updateSystem : addSystem;
        await apiMethod(this.formData);
        
        this.$message.success(this.isEditMode ? '更新成功' : '新增成功');
        this.dialogVisible = false;
        this.fetchSystems();
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error(this.isEditMode ? '更新失败' : '新增失败');
      } finally {
        this.submitting = false;
      }
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.queryData.pageSize = val;
      this.fetchSystems();
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.queryData.pageNum = val;
      this.fetchSystems();
    },
    
    // 格式化状态显示
    formatStatus(row) {
      return row.status === 1 ? '启用' : '停用';
    }
  },
  mounted() {
    this.fetchSystems();
  }
};
</script>

<style scoped>
.system-management {
  padding: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-button {
  margin-bottom: 15px;
}
</style>